document.addEventListener('DOMContentLoaded', () => {
    // const folderTree = document.getElementsByClassName('folder-tree')[0];
    // const fileList = document.getElementsByClassName('file-list')[0];
    const previewDiv = document.getElementsByClassName('preview')[0];
    const preImageDiv = document.querySelector('#one-img');
    const longImageDiv = document.querySelector('#long-img');
    const searchTxt = document.getElementById('code-search');
    const colNum = document.getElementById('col-num');
	const scrollContent = document.getElementById('tab_a_plan');
	const titleSpan = document.getElementById('av-title');
	const flagSpan = document.getElementById('av-flag');
	const ciliPanel = document.getElementById('cili_panel');
	
	const info_panel = document.querySelector('.movie-info-panel');
	const label_code = info_panel.querySelector('.lable-code span');
    const label_ri = info_panel.querySelector('.lable-ri span');
    const label_zh = info_panel.querySelector('.label-zh span');
    const label_shic = info_panel.querySelector('.lable-shic span');
    const label_yany = info_panel.querySelector('.lable-yany span');
    const label_jies = info_panel.querySelector('.lable-jies p');

    const copyRiBtn = info_panel.querySelector('.copy-ri');
    const copyZhBtn = info_panel.querySelector('.copy-zh');
	
	const dirBtn = document.getElementById('dir-btn');
	const playBtn = document.getElementById('play-btn');

    const coverImg = document.querySelector('.av-cover');
    const coverBtn = document.querySelector('.cover-btn');
	
	
	let selBookmark = null;
    let selTabIndex = 1;
	let selAvUrl = null;
	let dirUrl = null;
	let playUrl = null;

    // Function to preview the bookmark
    function previewBookmark(selTab, avcode, titleStr='none title', avUrl=null) {
        if (titleStr) {
            titleSpan.textContent = titleStr;
			document.title = titleStr + ' - JavBook';
        }
		selAvUrl = avUrl;
		
		let newCode = formatCode(avcode);
		
		startRequest(avcode, "弹窗");

        if (selBookmark != avcode) {
            // 增加预览视频
            // let videoSrc = "https://fivetiu.com/" + newCode + "/preview.mp4";
			let videoSrc = "https://fourhoi.com/" + newCode + "/preview.mp4";
            let preVideo = previewDiv.querySelector('#pre-video');
            preVideo.src = videoSrc;

            // 增加预览图
            // let imgSrc = "https://pedia-bucket-image.xfuse.fun/covers/" + newCode.toUpperCase() + ".jpg";
			let imgSrc = "https://fourhoi.com/" + newCode.toLowerCase() + "/cover.jpg";
            let img = previewDiv.querySelector('#pre-img');
            img.style.width = '100%';
            img.src = imgSrc;

            coverImg.src = imgSrc;
			
			searchFileFlag(newCode, function (ret, flag){
				if (ret == 0){
					flagSpan.textContent = `【${flag}】`;
				}
			});
			
			dirUrl = null;
			dirBtn.textContent = '-';
			dirBtn.style.color = '#367E7F';
			
			playUrl = null;
			playBtn.textContent = '-';
			playBtn.style.color = '#367E7F';
			
			search115Data(newCode, function (isRet, playAddr, pickcode, lookAddr, isRecord, isFavorite){
				 if (isRet){
					 // alert('搜索115成功。');
					 dirUrl = lookAddr;
					 dirBtn.style.color = '#946B13';
					 if (isRecord) {
						 dirBtn.textContent = '目■录';
					 }else{
						 dirBtn.textContent = '目-录';
					 }
					 
					 playUrl = playAddr;
					 playBtn.style.color = '#946B13';
					 if (isFavorite) {
						 playBtn.textContent = '播★放';
					 }else{
						 playBtn.textContent = '播-放';
					 }
				 }
			});
			
        }
        selBookmark = avcode;

		if (selTab <= 0) return;
		selTabIndex = selTab;
		localStorage.setItem('tab-select', selTabIndex);

        if (selTab == 1){
            // 增加预览图
			ciliPanel.classList.add('hide');
			preImageDiv.classList.remove('hide');
            preImageDiv.innerHTML = '';
            ciliPanel.innerHTML = '';
            searchFileList_javbus(newCode, 'preview', preImgCallback, finishCallback, infoCallback);

        }else if (selTab == 2){
            // 增加预览图
			ciliPanel.classList.remove('hide');
			preImageDiv.classList.remove('hide');
            preImageDiv.innerHTML = '';
            ciliPanel.innerHTML = '';
            searchFileList_javdb(newCode, 'preview', preImgCallback, finishCallback, infoCallback, ciliCallback);
			
			// let searchCode = formatCodeForNone(newCode);
			// ciliPanel.src = 'https://qjkkuqvc.2048173.xyz/search-' + searchCode + '-0-0-1.html'
			// ciliPanel.addEventListener('load', function (event){
            //     resizeFrame();
            // });

        }else if (selTab == 3){
            // 增加预览图
			ciliPanel.classList.add('hide');
			preImageDiv.classList.remove('hide');
            preImageDiv.innerHTML = '';
            ciliPanel.innerHTML = '';
            searchFileList(false, newCode, 'preview', preImgCallback, finishCallback, infoCallback);

        }else if (selTab == 4){
            longImageDiv.innerHTML = '';
            searchFileList(false, avcode, 'longimg', longImgCallback);
        }


        function preImgCallback(ret, imgName){
            if (ret == 1) {
                let avcode_00 = formatCodeFor00(newCode);
                previewUrl = `https://spic.hotoss.com/dmm/digital/video/${avcode_00}/${avcode_00}jp-${imgName}.jpg`;

            } else if (ret == 2) {
                previewUrl = imgName;

            } else if (ret == 0) {
                previewUrl = `http://localhost:10168/preview/${imgName}`;

			} else if (ret == 3) {
                previewUrl = `http://localhost:10168/preview/fengetiao.jpg`;
				
            } else {
                previewUrl = `http://localhost:10168/preview/error.jpg`;
            }

            let previewImg = document.createElement('img');
            previewImg.classList.add('preview-img');
            previewImg.classList.add('lazyload');
            previewImg.dataset.src = previewUrl;
            previewImg.src = 'http://localhost:10168/longimg/img_loading.jpg';

            preImageDiv.appendChild(previewImg);

        }
		
		function ciliCallback(ret, rowHtml){
            if (ret == 0) {
                ciliPanel.innerHTML += rowHtml;

            } else {
                previewUrl = `http://localhost:10168/preview/error.jpg`;
                let previewImg = document.createElement('img');
                previewImg.classList.add('preview-img');
                previewImg.classList.add('lazyload');
                previewImg.dataset.src = previewUrl;
                previewImg.src = 'icons/img_loading.jpg';

                ciliPanel.appendChild(previewImg);
            }

        }

        function finishCallback(res) {
            // 监听滚动事件
            lazyLoadImages(scrollContent);

        }
        function infoCallback(labelObj) {
			if (labelObj.lable_code !== '') label_code.textContent = labelObj.lable_code;
            if (labelObj.lable_ri !== '') label_ri.textContent = labelObj.lable_ri;
            if (labelObj.lable_zh !== '') label_zh.textContent = labelObj.lable_zh;
            if (labelObj.lable_shic !== '') label_shic.textContent = labelObj.lable_shic;
            if (labelObj.lable_yany !== '') label_yany.textContent = labelObj.lable_yany;
            if (labelObj.lable_jies !== '') label_jies.textContent = labelObj.lable_jies;

        }


        function longImgCallback(ret, imgName) {
            if (ret == 0) {
                previewUrl = `http://localhost:10168/longimg/${imgName}`;
            } else {
                previewUrl = `http://localhost:10168/longimg/error.jpg`;
            }

            let previewImg = document.createElement('img');
            previewImg.classList.add('prelong-img');
            previewImg.src = previewUrl;

            longImageDiv.appendChild(previewImg);
        }
    }

    function loadImage(img, filePath){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', filePath, true);
        xhr.responseType = 'blob';
        xhr.onload = function(e) {
            if (this.status === 200) {
                var blob = this.response;
                var reader = new FileReader();
                reader.onloadend = function() {
                    // var img = new Image();
                    img.src = reader.result;
                    // document.body.appendChild(img);
                };
                reader.readAsDataURL(blob);
            }
        };
        xhr.send();
    }
	
	function startRequest(avcode, fromStr) {
        let url = `http://localhost:10168/startrequest?avcode=${avcode}&fromstr=${fromStr}`;

        // 使用 fetch 发送 GET 请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析JSON
                return ;
            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('fetch error:', error);
            });

    }

    function searchFileList(isOther, javCode, cls, callback, callFinish = null, callInfo = null) {
        //保存查询关键词参数
        //GM_setValue("115_search_var", `${javId}|${javId2}|${javId3}|${javId4}`);

        let url = null;
        if (cls === 'preview') {
            url = `http://localhost:10168/search?imgcode=${javCode}`;
        } else if (cls === 'longimg') {
            url = `http://localhost:10168/longsearch?imgcode=${javCode}`;
        }
        if (!url) return;

        // 使用 fetch 发送 GET 请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                    callback(-2, null);
                }
                // 解析JSON
                return response.json();
            })
            .then(resultJson => {
                // 处理JSON数据
                if (resultJson.length > 0) {

                    for (let i = 0; i < resultJson.length; i++) {
                        let row = resultJson[i];

                        if (row) {
                            callback(0, row);
                        }
                    }
                    return true;

                }else {
                    throw new Error('Element not found');
                }

            })
            .then(res => {
                if (callFinish) {
                    setTimeout(function () {
                        callFinish(res);
                    }, 500);
                }

            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('fetch error:', error);
                if (isOther && error.message === 'Network response was not ok') {
                    searchFileList_javdb(javCode, cls, callback, callFinish, callInfo);

                } else if (isOther && error.message === 'Element not found') {
                    searchFileList_javdb(javCode, cls, callback, callFinish, callInfo);

                } else {
                    callback(-1, null);
                }
            });

    }

    function searchFileList_tor05(javCode, cls, callback, callFinish = null, callInfo = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/tor05/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
            })
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
                // 查询特定的元素
                const imgAaalist = doc.querySelectorAll('#preview-img .glightbox2');
                // 处理查询到的元素
                if (imgAaalist && imgAaalist.length > 0) {
                    console.log('Found element:', imgAaalist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    for (let i = 0; i < imgAaalist.length; i++) {
                        let aaa = imgAaalist[i];
                        callback(2, aaa.href);
                    }
                    return true;

                } else {
                    throw new Error('Element not found');
                }
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                callback(-1, null);

            } else if (error.message === 'Element not found') {
                callback(-1, null);

            } else {
                callback(-1, null);
            }
        });
    }

    function searchFileList_mfinder(javCode, cls, callback, callFinish = null, callInfo = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/mfinder/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
            })
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
				
                const lableObj = {};
                let sss = doc.querySelector('.text-warning');
                if (sss){
                    lableObj.lable_code = sss.textContent;
                }else {
                    lableObj.lable_code = '';
                }

                lableObj.lable_ri = '';

                sss = doc.querySelector('.card-header h3');
                if (sss){
                    lableObj.lable_zh = sss.textContent;
                }else {
                    lableObj.lable_zh = '';
                }

                sss = queryElementBytext(doc, '.col-md-3 p', '作品时长');
                if (sss){
                    lableObj.lable_shic = sss.textContent;
                }else {
                    lableObj.lable_shic = '';
                }

                sss = doc.querySelectorAll('.col-12 .m-title.m-0 a');
                if (sss && sss.length > 0){
                    let arr = Array.from(sss).map(obj => obj.textContent);
                    let str = '';
                    for (let i=0; i<arr.length; i++){
						let item = arr[i];
						if(i !== 0){
							str += '、';
						}
                        str += item;
                    }
                    lableObj.lable_yany = str;
                }else {
                    lableObj.lable_yany = '';
                }

                sss = doc.querySelector('.card-body h5');
                if (sss){
                    sss = sss.parentElement.querySelectorAll('p');
                }
                if (sss && sss.length > 0){
                    lableObj.lable_jies = sss[1].textContent;
                }else {
                    lableObj.lable_jies = '';
                }
                callInfo(lableObj);

                // 查询特定的元素
                const imglist = doc.querySelectorAll('.card-body .screenshot-link img');
                // 处理查询到的元素
                if (imglist && imglist.length > 0) {
                    console.log('Found element:', imglist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    let imgArr = Array.from(imglist);
                    imgArr.sort((a, b) => {
                        let anum = a.src.match(/-(\d{1,2}).jpg/)[1];
                        let bnum = b.src.match(/-(\d{1,2}).jpg/)[1];

                        return anum - bnum;
                    });
                    for (let i = 0; i < imgArr.length; i++) {
                        let img = imgArr[i];
                        imgAddrs = img.src.split('?');
                        callback(2, imgAddrs[0]);
                    }
                    return true;

                } else {
                    throw new Error('Element not found');


                }
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                callback(-1, null);

            } else if (error.message === 'Element not found') {
                callback(-1, null);

            } else {
                callback(-1, null);
            }
        });
    }

    function searchFileList_javbus(javCode, cls, callback, callFinish = null, callInfo = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/javbus/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
            })
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
				
				const lableObj = {};
                let sss = doc.querySelector('.col-md-3.info span[style]');
                if (sss){
                    lableObj.lable_code = sss.textContent;
                }else {
                    lableObj.lable_code = '';
                }
				
				sss = doc.querySelector('.container h3');
                if (sss){
                    lableObj.lable_ri = sss.textContent;
                }else {
                    lableObj.lable_ri = '';
                }

                lableObj.lable_zh = '';

                sss = queryElementBytext(doc, '.col-md-3.info p', '長度');
                if (sss){
                    lableObj.lable_shic = sss.textContent;
                }else {
                    lableObj.lable_shic = '';
                }

                sss = doc.querySelectorAll('.col-md-3.info span[onmouseover]');
                if (sss && sss.length > 0){
                    let arr = Array.from(sss).map(obj => obj.textContent.replace(/[\r\n\t]+/g, ''));
                    let str = '';
                    for (let i=0; i<arr.length; i++){
						let item = arr[i];
						if(i !== 0){
							str += '、';
						}
                        str += item;
                    }
                    lableObj.lable_yany = str;
                }else {
                    lableObj.lable_yany = '';
                }

                lableObj.lable_jies = '';
				
                callInfo(lableObj);
				
                // 查询特定的元素
                const imgAaalist = doc.querySelectorAll('#sample-waterfall a');
                // 处理查询到的元素
                if (imgAaalist && imgAaalist.length > 0) {
                    console.log('Found element:', imgAaalist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    for (let i = 0; i < imgAaalist.length; i++) {
                        let aaa = imgAaalist[i];
                        callback(2, aaa.href);
                    }
                    return imgAaalist.length;

                } else {
                    throw new Error('Element not found');


                }
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
				
				callback(3, null);
				callback(3, null);
				if (res % 2 == 1){
					callback(3, null);
				}
				// searchFileList_mfinder(javCode, cls, callback, callFinish, callInfo);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                searchFileList_mfinder(javCode, cls, callback, callFinish, callInfo);

            } else if (error.message === 'Element not found') {
                searchFileList_mfinder(javCode, cls, callback, callFinish, callInfo);

            } else {
                callback(-1, null);
            }
        });
    }
	
	function searchFileList_javdb(javCode, cls, callback, callFinish = null, callInfo = null, callCili = null) {
        // 请求URL
        // const url = 'http://localhost:10168/proxy?target_url=https://tor05.com/en/videos/' + javCode.toLowerCase();
        const url = 'http://localhost:10168/site/javdb_search/' + javCode.toLowerCase() + '.html';

        // 使用fetch API发送请求
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
				
            }).then(html => {
				const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const movieList = doc.getElementsByClassName('movie-list');
                if (movieList.length > 0) {
                    const firstElement = movieList[0];
                    const firstLink = firstElement.querySelector('a');
                    if (firstLink) {
                        const href = firstLink.getAttribute('href');
						const javdbCode = href.split('/').slice(-1)[0];
                        const fullUrl = 'http://localhost:10168/site/javdb/' + javdbCode + '.html';

                        return fetch(fullUrl);
                    }
                }
				throw new Error('Moive not found');
				
			})
			.then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 将响应转换为文本（如果是HTML页面）
                return response.text();
				
			})
            .then(html => {
                // 创建一个DOM解析器
                const parser = new DOMParser();
                // 将HTML字符串解析为DOM文档
                const doc = parser.parseFromString(html, 'text/html');
				
				const lableObj = {};
                let sss = doc.querySelector('.first-block span');
                if (sss){
                    lableObj.lable_code = sss.textContent;
                }else {
                    lableObj.lable_code = '';
                }
				
				sss = doc.querySelector('.origin-title');
                if (sss){
                    lableObj.lable_ri = sss.textContent;
                }else {
                    lableObj.lable_ri = '';
                }

                sss = doc.querySelector('.current-title');
                if (sss){
                    lableObj.lable_zh = sss.textContent;
                }else {
                    lableObj.lable_zh = '';
                }

                sss = queryElementBytext(doc, '.panel-block', '時長');
                if (sss){
                    lableObj.lable_shic = sss.textContent;
                }else {
                    lableObj.lable_shic = '';
                }

                sss = doc.querySelectorAll('.panel-block a[href^="/actors"]');
                if (sss && sss.length > 0){
                    let arr = [];
					let arr2 = [];
					for (obj of sss) {
						let nextElement = obj.nextElementSibling;
						if (nextElement && nextElement.textContent === '♀'){
							arr.push(obj.textContent);
						}else if (nextElement && nextElement.textContent === '♂'){
							arr2.push(obj.textContent);
						}
					}
                    let str = '';
                    for (let i=0; i<arr.length; i++){
						let item = arr[i];
						if(i !== 0){
							str += '、';
						}
                        str += item;
                    }
					for (let i=0; i<arr2.length; i++){
						let item = arr2[i];
						if(i == 0){
							str += '++';
						}else{
							str += '、';
						}
                        str += item;
                    }
                    lableObj.lable_yany = str;
                }else {
                    lableObj.lable_yany = '';
                }

                lableObj.lable_jies = '';
				
                callInfo(lableObj);
				
                // 磁力元素
				const ciliEles = doc.querySelectorAll('.item.columns');
                if (ciliEles && ciliEles.length > 0){
                    for (ciliEle of ciliEles){
                        let sizeSpan = ciliEle.querySelector('.meta');
                        if (sizeSpan){
                            sizeSpan.textContent = sizeSpan.textContent.replace('B', '').replace('M', 'm').replace(',', '      ------    ')
                        }

                        let tagsSpan = ciliEle.querySelector('.tags');
                        if (tagsSpan){
                            tagsSpan.textContent = '【【' + tagsSpan.textContent + '】】';
                        }

                        let btn = ciliEle.querySelector('.buttons.column button');
                        if (btn){
                            let magnetLink = btn.getAttribute('data-clipboard-text');
                            let imgHtml = '<img src="https://cdn.jsdelivr.net/gh/zxf10608/JavaScript/icon/115logo.ico" class="115offline" data-href='+magnetLink+' style="z-index:9123456789;display:inline-block;cursor:pointer;margin:0px 5px 2px;border-radius:50%;border:0px;vertical-align:middle;outline:none!important;padding:0px!important;height:20px!important;width:20px!important;left:0px!important;top:0px!important;" title="使用115网盘离线下载，右键复制地址\n'+magnetLink+'">';

                            let div = document.createElement('div');
                            div.className = "panel-footer";
                            div.innerHTML += imgHtml;
                            btn.parentElement.appendChild(div);
                        }
                        callCili(0, ciliEle.outerHTML);
                    }
                }else {
                    callCili(-1, null);
                }
				
				// 预览图元素
                const imgAaalist = doc.querySelectorAll('.tile-images.preview-images .tile-item');
                // 处理查询到的元素
                if (imgAaalist && imgAaalist.length > 0) {
                    console.log('Found element:', imgAaalist);
                    // 你可以在这里对elements进行进一步处理，比如获取其属性或内容
                    for (let i = 0; i < imgAaalist.length; i++) {
                        let aaa = imgAaalist[i];
                        callback(2, aaa.href);
                    }
                    return true;

                } else {
                    throw new Error('Element not found');
                }
				
            }).then(res => {
            if (callFinish) {
                setTimeout(function () {
                    callFinish(res);
                }, 500);
            }

        }).catch(error => {
            // 处理错误
            console.error('fetch error:', error);
            if (error.message === 'Network response was not ok') {
                callback(-1, null);

            } else if (error.message === 'Element not found') {
                callback(-1, null);

            } else {
                callback(-1, null);
            }
        });
    }
	
	function searchFileFlag(avcode, callFlag){
		// 使用 fetch 发送 GET 请求
		const url = 'http://localhost:10168/flag?avcode=' + avcode
        fetch(url)
            .then(response => {
                // 检查响应是否成功
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析JSON
                return response.json();
            })
            .then(resultJson => {
                // 处理JSON数据
                callFlag(0, resultJson.flag)
            })
            .catch(error => {
                // 处理请求过程中出现的错误
                console.error('fetch error:', error);
				callFlag(-1, null)
            });
		
	}
	
	function search115Data(javId, callback) {
		//异步请求搜索115番号 //115查询
		let javId2 = javId.replace(/(-)/g, ""); //把番号-去除，例如ABC-123 =》 ABC123
		let javId3 = javId.replace(/(-)/g, "00"); //把番号-替换为00，例如CCVR-065 =》 CCVR00065
		let javId4 = javId.replace(/(-)/g, "-0"); //把番号-替换为-0，例如DSVR-584 =》 DSVR-0584
		let search_var = `${javId}|${javId2}|${javId3}|${javId4}`;
		console.log("search_var", search_var)

		//保存查询关键词参数
		//GM_setValue("115_search_var", `${javId}|${javId2}|${javId3}|${javId4}`);

		//let url = `https://webapi.115.com/files/search?search_value=${javId}%20${javId2}%20${javId3}%20${javId4}&format=json`;
		let url = `http://localhost:10168/search115?search_value=${javId}%20${javId2}%20${javId3}%20${javId4}`;
		// 使用 fetch 发送 GET 请求
		fetch(url, {
			method: 'GET',
			headers: {
				"Cache-Control": "no-cache",
			}
		})
			.then(response => {
				// 检查响应是否成功
				if (!response.ok) {
					throw new Error('Network response was not ok');
					callback(false, null, null);
				}
				// 解析JSON
				return response.json();
			})
			.then(resultJson => {
				// 处理JSON数据
				if (resultJson.count > 0) {
					let pickcode = '';
					let cid = '';
					let isRecord = false
					let isFavorite = false
					let reg = new RegExp(search_var, "gi");
					for (let i = 0; i < resultJson.data.length; i++) {
						let row = resultJson.data[i];
						if (row.play_long && (row.n.search(reg) >= 0)) { //iv vdi ico play_long
							pickcode = row.pc;
							cid = row.cid

							if (row.m == "1"){
								isFavorite = true;
							}

							var flList = row.fl;
							if (flList){
								for (let j = 0; j < flList.length; j++) {
									var flagName = flList[j].name;
									if (flagName == "A▓▓" || flagName == "A██"){
										isRecord = true;
										break;
									}
								}
							}

							callback(true, `https://115vod.com/?pickcode=${pickcode}`, pickcode, `https://115.com/?cid=${cid}&offset=0&mode=wangpan`, isRecord, isFavorite);
							return;
						}
					}
				}
			})
			.catch(error => {
				// 处理请求过程中出现的错误
				console.error('There was a problem with your fetch operation:', error);
				callback(false, null, null);
			});

	}
	
	// 懒加载逻辑
    function lazyLoadImages(scroolElement) {
        let lazyLoadThrottleTimeout;

        // 检查内容是否在可视窗口内
        function isInViewport(element) {
            let top = element.offsetTop - scrollContent.scrollTop;
            if(top < (window.innerHeight * 2)) {
                return true;
            }

            return false;
        }

        function lazyLoad() {
            if(lazyLoadThrottleTimeout) {
                clearTimeout(lazyLoadThrottleTimeout);
            }

            lazyLoadThrottleTimeout = setTimeout(function() {
                const images = document.querySelectorAll('.lazyload');
                images.forEach(img => {
                    if (img.src.includes('img_loading.jpg') && isInViewport(img)) {
                        // const source = img.getAttribute('data-src');
                        const source = img.dataset.src;
                        img.src = source;
                        // img.removeAttribute('data-src');
                        img.classList.remove('lazyload');
                    }
                });

                if(images.length == 0) {
                    scroolElement.removeEventListener("scroll", lazyLoad);
                    scroolElement.removeEventListener("resize", lazyLoad);
                    scroolElement.removeEventListener("orientationChange", lazyLoad);
                }
            }, 200);
        }

        lazyLoad();
        scroolElement.addEventListener("scroll", lazyLoad);
        scroolElement.addEventListener("resize", lazyLoad);
        scroolElement.addEventListener("orientationChange", lazyLoad);
    }

    function formatCode(code){
        let newCode = code;
        if (code.indexOf('-') == -1){
            let numbers = code.match(/\d+/g);
            let chars = code.match(/[a-zA-Z]+/g);

            if (numbers && chars){
                newCode = chars[0] + "-" + numbers[0];
            }
        }

        return newCode;
    }

    function formatCodeForNone(code){
        let newCode = code;
        if (code.indexOf('-') == -1){
            let numbers = code.match(/\d+/g);
            let chars = code.match(/[a-zA-Z]+/g);

            if (numbers && chars){
                newCode = chars[0] + "%20" + numbers[0];
            }
        }

        return newCode;
    }
	
	function queryElementBytext(doc, flag, searchText){
        let elements = doc.querySelectorAll(flag);
        let filteredElements = Array.from(elements).filter(el => el.textContent.includes(searchText));
        if (filteredElements[0]){
            return filteredElements[0];
        }

        return null;
    }
	
	function getSelectedText() {
        // 使用window.getSelection()获取Selection对象
        const selection = window.getSelection();

        // 检查是否有选择的文本
        if (selection.rangeCount > 0) {
            // 获取第一个（也可能是唯一的）Range对象
            const range = selection.getRangeAt(0);

            // 使用Range对象的toString方法获取选择的文本
            // 注意：这里假设选择的是纯文本，没有包含其他元素或富文本格式
            const selectedText = range.toString();

            // 返回选择的文本
            return selectedText;
        }

        // 如果没有选择的文本，返回null或空字符串
        return null; // 或者 return '';
    }
	
	function popupWindow(newUrl, width = 1420, height = 960){
        var left = (window.screen.width - width)/2;
        var top = (window.screen.height - height)/2;
        var popupWindow = window.open(newUrl, '_blank', `left=${left}, top=${top} width=${width}, height=${height}`);
        // popupWindow.location.href = newUrl;
    }

    searchTxt.addEventListener('input', function (event){
        let searchStr = event.target.value;

        clearTimeout(inputTimer);
        inputTimer = setTimeout(function (){
            // searchBookmarkList(searchStr);
        }, 1000);

    });

    colNum.addEventListener('input', function (event){
        let colNum = event.target.value;

        preImageDiv.style.gridTemplateColumns = `repeat(${colNum},auto)`;
    });

    const tabButtons = document.querySelectorAll('.tab-button');
    const tabContents = document.querySelectorAll('.tab-content');

    tabButtons.forEach(button => {
        button.addEventListener('click', function() {
            button.addEventListener('click', function () {
                const targetTab = this.getAttribute('data-tab');
                const targetIndex = this.getAttribute('data-index');

                // Hide all tab contents
                tabContents.forEach(content => {
                    content.style.display = 'none';
                });

                document.getElementById(targetTab).style.removeProperty('display');

                // Optionally, remove active class from all buttons and add to the clicked button
                tabButtons.forEach(btn => btn.classList.remove('active'));
                this.classList.add('active');

                previewBookmark(targetIndex, selBookmark, null);
            });
        });
    });
	
	copyRiBtn.addEventListener('click', function (event){
		let avName = label_code.textContent;
		let titleStr = label_ri.textContent;
		const selected = getSelectedText();
		if (selected) {
			titleStr = selected.trim();
		}
		avName += ' ' + titleStr;
		let nvYan = label_yany.textContent;
		if (nvYan){
			avName += '==' + nvYan;
		}

		// const textCopied = ClipboardJS.copy(codeStr + ' ' + titleStr + '==' + nvYan);
		navigator.clipboard.writeText(avName);
	});

	copyZhBtn.addEventListener('click', function (event){
		let avName = label_code.textContent;
		let titleStr = label_zh.textContent;
		const selected = getSelectedText();
		if (selected) {
			titleStr = selected.trim();
		}
		avName += ' ' + titleStr;
		let nvYan = label_yany.textContent;
		if (nvYan){
			avName += '==' + nvYan;
		}

		// const textCopied = ClipboardJS.copy(codeStr + ' ' + titleStr + '==' + nvYan);
		navigator.clipboard.writeText(avName);
	});
	
	const addBookmarkBtn = info_panel.querySelector('#add_bookmark');
	addBookmarkBtn.addEventListener('click', function (event){
		if (selAvUrl){
			let bookmark = {
				'parentId': '2108',
				'title': titleSpan.textContent,
				'url': selAvUrl
			};
			
			// 向 popup.js 发送消息
			// chrome.runtime.sendMessage(bookmark);
			
			window.postMessage(bookmark, '*');
		}
		
	});
	
	const jumpCiliBtn = info_panel.querySelector('#jump_cilimao');
	jumpCiliBtn.addEventListener('click', function (event){
		var newCode = formatCodeForNone(selBookmark);
		var newUrl = "https://xiongmaoto.top/?searchstr=" + newCode;
		// var width = 900;
		// var height = 1100;
		// var left = (window.screen.width - width)/2;
		// var top = (window.screen.height - height)/2;
		// var popupWindow = window.open(newUrl, '_blank', `left=${left}, top=${top} width=${width}, height=${height}`);
		
		popupWindow(newUrl);
	});
	
	dirBtn.addEventListener('click', function (event){
		if(dirUrl){
			window.open(dirUrl, '_blank');
			window.close();
		}
	});
	
	playBtn.addEventListener('click', function (event){
		if(playUrl){
			window.open(playUrl, '_blank');
			window.close();
		}
	});

    coverBtn.addEventListener('click', function (){
        if (coverImg.style.display === 'none'){
            coverImg.style.display = 'block';
            coverBtn.textContent = '播放';
        }else {
            coverImg.style.display = 'none';
            coverBtn.textContent = '封面';
        }
    });

    function getQueryParam(param, defval='none') {
        const urlParams = new URLSearchParams(window.location.search);
        let paramStr = urlParams.get(param);
		
		if (paramStr) return paramStr;
		
		return defval;
    }

    let avcode = getQueryParam('avcode');
	let titleStr = getQueryParam('avtitle');
	let avUrl = getQueryParam('avurl');
	let tab = getQueryParam('tab');
	if (!isNaN(tab)) {
		let tabidx = parseInt(tab);
		selTabIndex = tabidx;
	}else{
		selTabIndex = localStorage.getItem('tab-select');
	}
    if (avcode !== 'none'){
		// Hide all tab contents
		const targetTabBtn = tabButtons[selTabIndex-1];
		const targetTab = targetTabBtn.getAttribute('data-tab');
		tabContents.forEach(content => {
			content.style.display = 'none';
		});
		document.getElementById(targetTab).style.removeProperty('display');

		// Optionally, remove active class from all buttons and add to the clicked button
		tabButtons.forEach(btn => btn.classList.remove('active'));
		targetTabBtn.classList.add('active');
				
        previewBookmark(selTabIndex, avcode, titleStr, avUrl);
		
    }
	
	// 为弹出窗口添加失去焦点的事件监听器
	// window.addEventListener('blur', function(event) {
		// 当弹出窗口失去焦点时，关闭它
		// this.close();
	// });
	
	// 监听在新窗口中的点击事件
	// window.document.addEventListener('click', function(event) {
		// 检查点击事件是否发生在窗口以外
		// if (!window.document.contains(event.target) && !window.document.compareDocumentPosition(event.target) === 4) {
			// 如果点击在窗口以外，关闭窗口
			// window.close();
		// }
	// }, true); // 第三个参数 true 表示在捕获阶段监听事件

});